package com.jic.market.common.util;

import com.alibaba.fastjson.JSONObject;

/**
 *
 */
public class JSONObjectUtils {
    public JSONObjectUtils() {
    }

    public static Object getValue(JSONObject jsonObject, String path, String pathSep) {
        String[] paths = path.split(pathSep);
        return getValue(jsonObject, paths);
    }

    public static Object getValue(JSONObject jsonObject, String[] paths) {
        int i = 0;

        JSONObject obj;
        for(obj = jsonObject; i < paths.length - 1; obj = obj.getJSONObject(paths[i++])) {
            if (obj == null) {
                return null;
            }
        }

        return obj == null ? null : obj.get(paths[i]);
    }

    public static void putValue(JSONObject jsonObject, String path, String pathSep, Object value) {
        String[] paths = path.split(pathSep);
        putValue(jsonObject, paths, value);
    }

    public static void putValue(JSONObject jsonObject, String[] paths, Object value) {
        int i = 0;

        JSONObject json;
        Object jobj;
        for(json = jsonObject; i < paths.length - 1; json = (JSONObject)jobj) {
            String key = paths[i++];
            jobj = json.get(key);
            if (jobj == null || !(jobj instanceof JSONObject)) {
                jobj = new JSONObject();
                json.put(key, jobj);
            }
        }

        json.put(paths[i], value);
    }
}
